package web_config

import (
	"chain_bridge_service/internal/code"
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/pkg/validation"
	"chain_bridge_service/internal/services/web_config"
	"net/http"
)

type CreateWebConfigData struct {
	Name string
	Url  string
}

type createResponse struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

type createRequest struct {
	Content string
}

func (h *handler) Create() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createRequest)
		res := new(createResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				validation.Error(err)).WithError(err),
			)
			return
		}
		data := new(web_config.WebConfigData)
		data.Content = req.Content

		err := h.webService.Create(ctx, data)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.CreateUserError,
				code.Text(code.CreateUserError)).WithError(err),
			)
			return
		}

		res.Code = code.StatusOK
		res.Data = nil
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}

func (h *handler) GetLatest() core.HandlerFunc {
	return func(ctx core.Context) {
		res := new(createResponse)

		data, err := h.webService.GetLatest(ctx)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.CreateUserError,
				code.Text(code.CreateUserError)).WithError(err),
			)
			return
		}

		res.Code = code.StatusOK
		res.Data = data
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
